package org.raymond.iworks.study.basic.structure.stack;

/**
 * @author raymond
 * @version V1.0
 * @Description:
 * 实现思路分析:
 * 1, 使用数组来模拟栈
 * 2, 定义一个top来表示栈顶,初始化为-1.
 * 3, 入栈的操作，当有数据加入到栈时, top++; stack[top]=data;
 * 4, 出栈的操作, val=stack[top]; top--; return val;
 */
public class ArrayStack2 {
    private int max;
    private int top;
    private int[] array;

    public ArrayStack2(int max){
        this.max = max;
        top = -1;
        array = new int[max];
    }

    public void push(int i){
        if(isFull()){
            System.err.println("栈已满");
            return;
        }
        top++;
        array[top] = i;
    }

    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("stack is empty");
        }
        int tmp = array[top];
        top--;
        return tmp;
    }

    public int peek(){
        if(isEmpty()){
            throw new RuntimeException("stack is empty");
        }
        return array[top];
    }
    public boolean isFull(){
        return top == max-1;
    }

    public boolean isEmpty(){
        return top == -1;
    }

    public void show(){
        if(isEmpty()){
            System.err.println("stack is empty");
            return;
        }
        for(int i=top; i>=0; i--){
            System.out.println("->"+array[i]);
        }
    }

    // 返回运算符的优先级
    // 优先级使用数字表示,数字越大,则优先级越高
    public static int priority(int oper){
        if(oper=='*' || oper=='/'){
            return 1;
        }else if(oper == '+' || oper == '-'){
            return 0;
        }else{
            return -1; //假定目前只有+-*/
        }
    }
    public static boolean isOper(char val){
        return val=='+'||val=='-'||val=='*'||val=='/';
    }
    public static int cal(int num1, int num2, int oper){
        int res = 0;
        switch (oper){
            case '+':
                res = num1+num2;
                break;
            case '-':
                res = num2-num1; // 注意顺序
                break;
            case '*':
                res = num1*num2;
                break;
            case '/':
                res = num2/num1;
                break;
            default:
                break;
        }
        return res;
    }
}
